import 'package:get/get.dart';
import '../../function/state/user_state.dart';
import '../../function/state/follow_state.dart';
import '../../function/state/like_state.dart';
import '../../function/state/post_state.dart';
import '../../function/model/user_model.dart';
import '../../function/model/post_model.dart';

/// 个人资料页面控制器
class ProfilePageController extends GetxController {
  final UserState _userState = Get.find<UserState>();
  final FollowState _followState = Get.find<FollowState>();
  final LikeState _likeState = Get.find<LikeState>();
  final PostState _postState = Get.find<PostState>();

  // 页面标题
  final RxString pageTitle = 'Profile'.obs;

  // 当前选中的标签页
  final RxInt currentTabIndex = 0.obs;

  @override
  void onInit() {
    super.onInit();
    _initializePageData();
  }

  /// 初始化页面数据
  void _initializePageData() {
    // 只有在用户已登录时才设置用户ID
    if (_userState.isLoggedIn && _userState.currentUser != null) {
      _followState.setCurrentUserId(_userState.currentUser!.id);
      _likeState.setCurrentUserId(_userState.currentUser!.id);
    }
  }

  /// 获取当前用户
  UserModel? get currentUser => _userState.currentUser;

  /// 是否已登录
  bool get isLoggedIn => _userState.isLoggedIn;

  /// 获取关注数量
  int get followingCount => _followState.followingCount;

  /// 获取粉丝数量
  int get followersCount => _followState.followersCount;

  /// 获取点赞数量（用户收获的点赞数）
  int get likesReceivedCount {
    if (currentUser == null) return 0;
    return _likeState.getUserTotalLikes(currentUser!.id);
  }

  /// 获取用户发布的帖子（按日期分组）
  Map<String, List<PostModel>> get userPostsByDate {
    if (currentUser == null) return {};
    final posts =
        _postState.allPosts
            .where((post) => post.userId == currentUser!.id)
            .toList()
          ..sort((a, b) => b.publishTime.compareTo(a.publishTime));

    return _groupPostsByDate(posts);
  }

  /// 获取用户点赞的帖子（按日期分组）
  Map<String, List<PostModel>> get userLikedPostsByDate {
    if (currentUser == null) return {};
    final likedPostIds = _likeState.getLikedPostIds();
    final posts =
        _postState.allPosts
            .where((post) => likedPostIds.contains(post.id))
            .toList()
          ..sort((a, b) => b.publishTime.compareTo(a.publishTime));

    return _groupPostsByDate(posts);
  }

  /// 按日期分组帖子
  Map<String, List<PostModel>> _groupPostsByDate(List<PostModel> posts) {
    final Map<String, List<PostModel>> groupedPosts = {};

    for (final post in posts) {
      final dateKey = _formatDateKey(post.publishTime);
      if (!groupedPosts.containsKey(dateKey)) {
        groupedPosts[dateKey] = [];
      }
      groupedPosts[dateKey]!.add(post);
    }

    return groupedPosts;
  }

  /// 格式化日期键
  String _formatDateKey(DateTime date) {
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    final yesterday = today.subtract(Duration(days: 1));
    final postDate = DateTime(date.year, date.month, date.day);

    if (postDate == today) {
      return 'Today';
    } else if (postDate == yesterday) {
      return 'Yesterday';
    } else {
      return _formatDateWithMonthAbbreviation(date);
    }
  }

  /// 格式化日期为月份缩写形式
  String _formatDateWithMonthAbbreviation(DateTime date) {
    const monthAbbreviations = [
      'Jan.',
      'Feb.',
      'Mar.',
      'Apr.',
      'May',
      'Jun.',
      'Jul.',
      'Aug.',
      'Sep.',
      'Oct.',
      'Nov.',
      'Dec.',
    ];

    final monthAbbr = monthAbbreviations[date.month - 1];
    return '$monthAbbr ${date.day}';
  }

  /// 格式化时间显示
  String formatTime(DateTime dateTime) {
    final hour = dateTime.hour.toString().padLeft(2, '0');
    final minute = dateTime.minute.toString().padLeft(2, '0');
    return '$hour:$minute';
  }

  /// 切换标签页
  void switchTab(int index) {
    currentTabIndex.value = index;
  }

  /// 前往登录页面
  void goToLogin() {
    Get.toNamed('/user-access');
  }

  /// 前往设置页面
  void goToSettings() {
    Get.toNamed('/settings');
  }

  /// 播放视频
  void playVideo(PostModel post) {
    if (post.resourceType == ResourceType.video) {
      Get.toNamed('/video-player', arguments: post);
    }
  }

  /// 跳转到帖子详情页面
  void goToPostDetail(PostModel post) {
    Get.toNamed('/post-detail', arguments: post);
  }

  /// 跳转到关注列表页面
  void goToFollowingList() {
    Get.toNamed('/follow-list', arguments: 'following');
  }

  /// 跳转到粉丝列表页面
  void goToFollowersList() {
    Get.toNamed('/follow-list', arguments: 'followers');
  }
}
